package com.item.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.base.dialect.PaginationSupport;
import com.base.util.DateUtil;
import com.item.dao.MobileVerifyMapper;
import com.item.dao.NoteCommentMapper;
import com.item.dao.PostCommentMapper;
import com.item.dao.PostMapper;
import com.item.dao.UnreadMapper;
import com.item.dao.UserMapper;
import com.item.dao.model.MobileVerify;
import com.item.dao.model.MobileVerifyExample;
import com.item.dao.model.NoteComment;
import com.item.dao.model.NoteCommentExample;
import com.item.dao.model.Post;
import com.item.dao.model.PostComment;
import com.item.dao.model.PostCommentExample;
import com.item.dao.model.PostExample;
import com.item.dao.model.Unread;
import com.item.dao.model.User;
import com.item.dao.model.UserExample;
import com.item.mobile.MAppQuestion;
import com.item.util.ConstantResources;
import com.item.util.MobileLock;
import com.item.util.MyDateUtils;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
	private MobileVerifyMapper verifyMapper;
    @Autowired
    private PostCommentMapper postCommentMapper;
    @Autowired
    private NoteCommentMapper noteCommentMapper;
    @Autowired
    private UnreadMapper unreadMapper;

    private static final Logger logger = Logger.getLogger(UserService.class);

    public int countByExample(UserExample example) {
        return this.userMapper.countByExample(example);
    }

    public User selectByPrimaryKey(String id) {
        return this.userMapper.selectByPrimaryKey(id);
    }

    public List<User> selectByExample(UserExample example) {
        return this.userMapper.selectByExample(example);
    }

    public int deleteByPrimaryKey(String id) {
        return this.userMapper.deleteByPrimaryKey(id);
    }

    public int updateByPrimaryKeySelective(User record) {
        return this.userMapper.updateByPrimaryKeySelective(record);
    }

    public int updateByPrimaryKey(User record) {
        return this.userMapper.updateByPrimaryKey(record);
    }

    public int deleteByExample(UserExample example) {
        return this.userMapper.deleteByExample(example);
    }

    public int updateByExampleSelective(User record, UserExample example) {
        return this.userMapper.updateByExampleSelective(record, example);
    }

    public int updateByExample(User record, UserExample example) {
        return this.userMapper.updateByExample(record, example);
    }

    public int insert(User record) {
        return this.userMapper.insert(record);
    }

    public int insertSelective(User record) {
        return this.userMapper.insertSelective(record);
    }
    
    /**
     *  create new user with increment user's account
     * @param user
     * @return
     */
    public User getNextAccount(User user) {
    	synchronized (MobileLock.USER_ACCOUNT_LOCK) {
    		int count = this.userMapper.countByExample(new UserExample());
    	
    		if(count == 0) { //first user
    			user.setAccount("YDD0000001");
    		} else { //progressive increase account number
    			PaginationSupport.setContext(1, 1, null);
    			UserExample example = new UserExample();
    			example.setOrderByClause("create_time DESC");
    			User lastUser = this.userMapper.selectByExample(example).get(0);
    			String account = String.format("YDD%07d", 
    					Integer.parseInt(lastUser.getAccount().replaceAll("[^\\d]", "")) + 1);
    			user.setAccount(account);
    			if(StringUtils.isBlank(user.getPhone()) && StringUtils.isBlank(user.getQqAccount()) &&StringUtils.isBlank(user.getWbAccount())&&StringUtils.isBlank(user.getWxAccount())){
    				user.setNickname(account);
    			}
    		}
    		user.setSubjectEng(MAppQuestion.SUBJECTS[0]);
    		user.setSubjectPolity(MAppQuestion.SUBJECTS[3]);
    		user.setCreateTime(new Date(System.currentTimeMillis()));
    		user.setStartDate(user.getCreateTime());
    		user.setEndDate(DateUtil.parseDate(ConstantResources.OVERDATE, "yyyy-MM-dd"));
    		this.userMapper.insertSelective(user);
    		//再插入一条未读消息记录
    		Unread read = new Unread();
    		read.setModule1(0);
    		read.setModule2(0);
    		read.setModule3(0);
    		read.setModule4(0);
    		read.setCreateTime(user.getCreateTime());
    		read.setUserid(user.getId());
    		this.unreadMapper.insert(read);
		}
    	
    	return user;
    }
    
    public boolean mobileUserVerify(String appid,String userid,String verify,String deviceid){
		User user = this.userMapper.selectByPrimaryKey(userid);
		if(user!=null){
			MobileVerifyExample example = new MobileVerifyExample();
			example.createCriteria().andUserIdEqualTo(userid).andVerifyEqualTo(verify)
			.andDeviceIdEqualTo(deviceid);
			List<MobileVerify> list = verifyMapper.selectByExample(example);
			if(list!=null && list.size()>0){
				return true;
			}
		}
    	return false;
    }
    
    //synchronize user info
    public void synchronizeInfo(String userid, String nickname, String headimg) {
    	NoteCommentExample ncex = new NoteCommentExample();
    	NoteCommentExample.Criteria criteria = ncex.createCriteria().andUseridEqualTo(userid);
    	NoteComment comment = new NoteComment();
    	if(StringUtils.isNotBlank(nickname)){
    		comment.setUsername(nickname);
    	}
    	if(StringUtils.isNotBlank(headimg)){
    		comment.setUserimg(headimg);
    	}
    	this.noteCommentMapper.updateByExampleSelective(comment, ncex);
    	//post user info
//    	PostExample postExample =
//    			new PostExample();
//    	postExample.createCriteria().andUseridEqualTo(userid);
//    	Post post = new Post();
//    	post.setHeadimg(headimg);
//    	post.setNickname(nickname);
////    	post.setSex(sex);
////    	this.postMapper.updateByExampleSelective(post, postExample);
//    	
//    	//comment info
//    	PostCommentExample postCommentExample =
//    			new PostCommentExample();
//    	
//    	//commenter info
//    	postCommentExample.createCriteria()
//    	.andUseridEqualTo(userid);
//    	PostComment comment = new PostComment();
//    	comment.setNickname(nickname);
//    	comment.setHeadimg(headimg);
//    	comment.setSex(sex);
////    	this.postCommentMapper
////    	.updateByExampleSelective(comment, postCommentExample);
//    	
//    	//replied user info
//    	postCommentExample.clear();
//    	postCommentExample.createCriteria()
//    	.andReplyIdEqualTo(userid);
//    	comment.setNickname(null);
//    	comment.setHeadimg(null);
//    	comment.setReplyNickname(nickname);
//    	this.postCommentMapper
//    	.updateByExampleSelective(comment, postCommentExample);
    }
}